<?php

//
// +---------------------------------------------------------+
// | 开发组
// +---------------------------------------------------------+
// | Copyrigh  (c)  2020 The PHP Group
// +---------------------------------------------------------+
// | 商户 代理商
// +---------------------------------------------------------+
// | zxc
// | php后端开发
// |
// +———————————————————+
//

namespace App\Models\Admin;

use App\Tools\AliSms;
use App\Tools\Financial;
use App\Tools\Prstatic;
use Illuminate\Database\Eloquent\Model;

class StoreOrder extends Model
{

    protected $table = 'store_order';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    /**
     * 获取列表
     * @param $where
     * @param int $limit
     * @return mixed
     */
    public static function getPageList($where, $limit = 15)
    {
        $data = [];
        if ($where['order_sn']) {
            $data[] = ['o.order_sn', '=', $where['order_sn']];
        }
        if ($where['stock_order_sn']) {
            $data[] = ['o.stock_order_sn', '=', $where['stock_order_sn']];
        }
        if ($where['src_order_no']) {
            $data[] = ['o.src_order_no', '=', $where['src_order_no']];
        }
        if ($where['store_id']) {
            $data[] = ['s.id', '=', $where['store_id']];
        }
        if ($where['tracking_number']) {
            $data[] = ['o.tracking_number', '=', $where['tracking_number']];
        }
        if ($where['order_mobile']) {
            $data[] = ['o.order_mobile', '=', $where['order_mobile']];
        }
        $start = $where['start_time'] ? strtotime($where['start_time']) : 0;
        $end = $where['end_time'] ? strtotime($where['end_time']) : time();
        $db = self::from('store_order as o')
            ->select(['o.*', 's.store_name', 's.discount_rate'])
            ->leftJoin('store as s', 's.id', '=', 'o.store_id')
            ->where($data)->whereBetween('o.created_at', [$start, $end])
            ->orderBy('o.id', 'desc');
        if ($limit == 0) {
            $list = $db->get();
        } else {
            $list = $db->paginate($limit);
        }
        foreach ($list as $key => $vv) {
            $list[$key]['order_status_name'] = Prstatic::$orderStatus[$vv['order_status']];
            $list[$key]['order_status_color'] = Prstatic::$color[$vv['order_status']];
            $list[$key]['send_status_name'] = Prstatic::$orderSendStatus[$vv['send_status']];
            $list[$key]['send_status_color'] = Prstatic::$color[$vv['send_status']];
        }
        return $list;
    }

    /**
     * 获取信息
     * @param $id
     */
    public static function getInfoById($id)
    {
        $info = self::where(['id' => $id])->first();
        if ($info) {
            $info = $info->toArray();
            // 获取代理商信息

            $info['order_status_name'] = Prstatic::$orderStatus[$info['order_status']];
            $info['order_status_color'] = Prstatic::$color[$info['order_status']];
            $info['send_status_name'] = Prstatic::$orderSendStatus[$info['send_status']];
            $info['send_status_color'] = Prstatic::$color[$info['send_status']];
            return $info;
        }
        return [];
    }

    /**
     * 修改消息
     */
    public static function editInfo($data)
    {
        $expressMap = [
            1 => '圆通/中通',
            2 => '顺丰',
            3 => '德邦'
        ];
        
        $info['order_amount'] = $data['order_amount'];
        $info['express_id'] = $data['express_id']; //快递id 1=圆通/中通 2=顺丰 3=德邦
        $info['express_company'] = $expressMap[$data['express_id']] ?? ''; //根据快递ID自动设置快递公司名称
        $info['goods_pay_amount'] = $data['goods_pay_amount'] ?? $data['order_amount'];
        $info['freight'] = $data['freight'];
        $info['total_number'] = $data['total_number'];
        $info['order_name'] = $data['order_name'];
        $info['order_mobile'] = $data['order_mobile'];
        $info['order_province'] = $data['order_province'];
        $info['order_city'] = $data['order_city'];
        $info['order_area'] = $data['order_area'];
        $info['order_address'] = $data['order_address'];
        $info['tracking_number'] = $data['tracking_number'];
        $info['remark'] = $data['remark'];
        $info['updated_at'] = time();
        
        // 计算商品总金额（除非已确认金额）
        $orderAmountType = isset($data['order_amount_type']) && $data['order_amount_type'] == 1;
        
        if ($orderAmountType) {
            // 使用传入的商品金额
            $info['goods_amount'] = $data['goods_amount'];
            // 同时使用传入的订单金额和支付金额
            $info['order_amount'] = $data['order_amount'];
            $info['goods_pay_amount'] = $data['goods_pay_amount'] ?? $data['order_amount'];
        } else {
            // 重新计算商品总金额
            $goods_amount = 0;
            foreach ($data['goods'] as $goods) {
                if ($goods['is_give'] != 1) { // 非赠送商品才计入金额
                    $goods_amount += $goods['goods_price'] * $goods['goods_number'];
                }
            }
            $info['goods_amount'] = $goods_amount;
        }
        if ($data['id']) {
            return self::where(['id' => $data['id']])->update(array_filter($info));
        }
        return false;
    }

    /**
     * 出库单
     *
     * @return void
     */
    public static function successSend($order_id)
    {
        $orderInfo = self::where(['id' => $order_id])->select(['order_mobile', 'order_sn', 'express_company', 'tracking_number'])->first();
        if ($orderInfo) {
            AliSms::sendList($orderInfo['order_mobile'], 4, $orderInfo['order_sn'], ['expressCompany' => $orderInfo['express_company'], 'espressOrder' => $orderInfo['tracking_number']]);
        }
        return true;
    }
}